<template>
<teleport to="#backTop">
    <transition name="fade">
        <div
            v-show="show"
            class="back-top iconfont"
            @click="back"
        >
        &#xe631;
        </div>
    </transition>
</teleport>
</template>

<script>
import { defineComponent, onUnmounted ,ref} from 'vue'

export default defineComponent({
  setup() {
    const node = document.createElement('div')
    node.id = 'backTop'
    document.body.appendChild(node)
    const show=ref(false)
    const backTop=()=>{
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        if(scrollTop>100){
            show.value=true
        }else{
            show.value=false
        }
    }
    document.addEventListener('scroll',backTop)
    const back=()=>{
        console.log('回到')
        let toElement = document.querySelector('body');
        toElement.scrollIntoView({
            behavior: 'smooth',
            block: 'start',
            inline: 'nearest'
        })
    }
    onUnmounted(() => {
      document.body.removeChild(node)
      document.removeEventListener("scroll", backTop);
    })
    return {
        show,
        back
    }
  },

})
</script>

<style>
.back-top {
    width: 50px;
    height: 50px;
    z-index: 100;
    position: fixed;
    bottom:20px;
    right:20px;
    border-radius: 50%;
    background-color:rgba(0,0,0,.5);
    transition: all .3s;
    cursor: pointer;
    text-align: center;
    line-height: 50px;
    color: #fff;
    font-size: 25px!important;
}
.back-top:hover{
    line-height: 45px;
    background-color:rgba(0,0,0,.8);
}

</style>
